package com.jtlrm.ckd.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.DataShenHeEntity;
import com.jtlrm.ckd.entity.NewsEntity;
import com.jtlrm.ckd.entity.PageEntity;
import com.jtlrm.ckd.entity.SuiFangPaiBanEntity;
import com.jtlrm.ckd.entity.event.ShenHeRemarkMessage;
import com.jtlrm.ckd.entity.event.ShenHeUpdate;
import com.jtlrm.ckd.entity.event.YinShiUpdateMessage;
import com.jtlrm.ckd.mvp.model.ShuJuShenHeModel;
import com.jtlrm.ckd.mvp.view.adapter.AddSuiFangAdapter;
import com.jtlrm.ckd.mvp.view.adapter.ShuJuShenHeAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 这块经讨论不要模糊查询
 */
public class ShuJuShenHeActivity extends TitleBarActivity {

    private final static String PILIANGE = "批量审核";
    private final static String CANCEL = "取消";
    @BindView(R.id.bottom)
    RelativeLayout bottmContainer;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    ShuJuShenHeAdapter adapter;
    @BindView(R.id.not_pass)
    TextView notPassT;
    @BindView(R.id.pass)
    TextView passT;
    @BindView(R.id.check_all)
    CheckBox checkBox;
    ShuJuShenHeModel shuJuShenHeModel;
    private int pageNum = 1;
    private int pageSize = 12;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "数据审核";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_shu_ju_shen_he);
    }

    @Override
    protected void initView() {
        shuJuShenHeModel = new ShuJuShenHeModel();
        setEditStatus(false);
        titleBar.tvRight.setVisibility(View.VISIBLE);
        adapter = new ShuJuShenHeAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(createItemDecoration());
        recyclerView.setAdapter(adapter);
        EventBusUtil.register(this);
    }


    @Override
    protected void obtainData() {
    }

    @Override
    protected void initEvent() {
        titleBar.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setEditStatus(!isEdite());
            }
        });
        notPassT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, ShenHeFalseActivity.class));
            }
        });
        passT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shenHe(true, "");
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(context, ShuJuShenHeDetailActivity.class));
            }
        });
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                loadData();
            }
        });
        smartRefreshLayout.autoRefresh();
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBox.isChecked()) {
                    selectAll(true);
                } else {
                    selectAll(false);
                }
            }
        });
        adapter.setUpdateSelect(new ShuJuShenHeAdapter.UpdateSelect() {
            @Override
            public void update() {
                updateSelectNum();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ShenHeRemarkMessage message) {
        if (message != null && isEdite()) {
            String remark = message.getRemark();
            shenHe(false, remark);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ShenHeUpdate message) {
        if (message != null && !isEdite()) {
           smartRefreshLayout.autoRefresh();
        }
    }


    private void shenHe(boolean pass, String remark) {
        List<DataShenHeEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            showToast("数据为空，不能提交");
            return;
        }
        String selectId = "";
        for (DataShenHeEntity entity : data) {
            if (entity.isSelected()) {
                if (notEmpty(selectId)) {
                    selectId = selectId + "," + entity.getTreatmentId();
                } else {
                    selectId = entity.getTreatmentId();
                }
            }
        }
        if (!notEmpty(selectId)) {
            showToast("至少选择一人才能提交");
            return;
        }
        showLoadingDialog("提交中");
        shuJuShenHeModel.shenHe(selectId, remark, pass ? 1 : 0, new CommonObserver<String>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(String data) {
                showToast("提交成功");
                dismissLoadingDialog();
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }

    /**
     * 是否全部选中
     *
     * @param isSelectAll
     */
    private void selectAll(boolean isSelectAll) {
        List<DataShenHeEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            return;
        }
        if (isSelectAll) {
            for (DataShenHeEntity entity : data) {
                entity.setSelected(true);
            }
        } else {
            for (DataShenHeEntity entity : data) {
                entity.setSelected(false);
            }
        }
        adapter.notifyDataSetChanged();
        updateSelectNum();
    }


    /**
     * 更新选中人数
     */
    private void updateSelectNum() {
        List<DataShenHeEntity> data = adapter.getData();
        if (data == null || data.size() == 0) {
            setText(checkBox, "全选(0人)");
            return;
        }
        int num = 0;
        for (DataShenHeEntity entity : data) {
            if (entity.isSelected()) {
                ++num;
            }
        }
        setText(checkBox, "全选(" + num + "人)");
        if (num != 0&& num == data.size()){
            checkBox.setChecked(true);
        }else {
            checkBox.setChecked(false);
        }
    }


    private void loadData() {
        shuJuShenHeModel.queryAddSuiFangList("", pageNum, pageSize, new CommonObserver<PageEntity<List<DataShenHeEntity>>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                closeFrshorLoadmore();
            }

            @Override
            public void onResult(PageEntity<List<DataShenHeEntity>> data) {
                if (pageNum == 1) {
                    adapter.replaceData(data.getItems());
                } else {
                    adapter.addData(data.getItems());
                }
                if (data.getItems().size() < pageSize) {
                    smartRefreshLayout.setEnableLoadmore(false);
                } else {
                    smartRefreshLayout.setEnableLoadmore(true);
                }
                updateSelectNum();
                closeFrshorLoadmore();
            }
        }, lifecycleSubject);
    }

    /**
     * 是否属于审核状态
     *
     * @return true 处于审核状态
     */
    public boolean isEdite() {
        if (CANCEL.equals(titleBar.tvRight.getText() + "")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置审核状态 true 处于审核中
     *
     * @param status
     */
    private void setEditStatus(boolean status) {
        if (status) {
            // 可编辑
            bottmContainer.setVisibility(View.VISIBLE);
            titleBar.tvRight.setText(CANCEL);
        } else {
            bottmContainer.setVisibility(View.GONE);
            titleBar.tvRight.setText(PILIANGE);
        }
        if (adapter != null) {
            adapter.setEdite(status);
        }
    }

    protected RecyclerView.ItemDecoration createItemDecoration() {
        return new DefaultItemDecoration(ContextCompat.getColor(this, R.color.margin_background), 2, 2, -1);
    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }


}
